from flask import Flask, request, jsonify, send_from_directory, render_template
import os
import startcode
import sys
import pose_recognition as pr
import base64
import io
import cv2
import numpy as np
from PIL import Image
from matplotlib.animation import FuncAnimation

video_path = ""
side = 0
height_real = 0

app = Flask(__name__)
# 创建一个文件夹invideo，用来存放用户上传的视频
app.config['INVIDEO_FOLDER'] = 'invideo'
if not os.path.exists(app.config['INVIDEO_FOLDER']):
    os.makedirs(app.config['INVIDEO_FOLDER'])

# 访问根目录时，调用index()函数
@app.route('/')
def index():
    return render_template('index.html')

print("位置一")
@app.route('/hello')

def hohello_world2():
    # print("weizhi 2")
    return render_template("home11.html")

@app.route('/data', methods=['GET'])
def data():
    # 这里需要实现从后端获取数据的逻辑
    # 例如，从全局变量或数据库中获取数据
    data = {
        'attacks_count':     pr.attacks_count,  # 示例数据
        'sum_distance':      pr.global_sum_distance,
        'right_hand_angle':  pr.global_right_hand_angle,
        'right_ankle_angle': pr.global_right_ankle_angle,
        'left_ankle_angle':  pr.global_left_ankle_angle,
        'right_knee_angle':  pr.global_right_knee_angle,
        'left_knee_angle':   pr.global_left_knee_angle,
        'right_shoulder':    pr.global_right_shoulder,
        'left_shoulder':     pr.global_left_shoulder,
        'right_hip':         pr.global_right_hip,
        'left_hip':          pr.global_left_hip
    }
    return jsonify(data)

# @app.route('/plot', methods=['GET'])
# def plot():
#     # 这里你需要根据实际情况调用 PoseDetector 类并获取图像数据
#     # 假设 detector 是你的 PoseDetector 实例
#     detector = pr.PoseDetector(video_path, height_real, side)
#     image_base64 = detector.update_plot(None)  # 这里可能需要根据你的实际代码调整
#     return jsonify(image=image_base64)
# video = request.files['video']
# video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
# side = request.form.get('side', type=int)
# height_real = request.form.get('height', type=int)
# 当有POST请求时，执行upload_video
@app.route('/invideo', methods=['POST'])
def upload_video():
    global video_path
    global side
    global height_real
    # 如果video为空
    if 'video' not in request.files:
        return jsonify({'error': '没有视频被上传'}), 400
    
    # 获取网页上传的视频
    video = request.files['video']
    
    # 获取网页上传的side
    side = request.form.get('side', type=int)
    # print(type(side))
    # 获取网页上传的真实身高
    height_real = request.form.get('height', type=int)
    # print(type(height_real))


    if not video:
        return jsonify({'error': '没有视频被上传'}), 400

    if video.filename == '':
        return jsonify({'error': '没有选择视频文件'}), 400
    
    print("视频文件有效，准备保存")

    if video:
        # 将服务器invideo文件夹与视频文件名组合   **invideo/video.filename   invideo/视频文件名
        video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
        # print(type(video_path))
        video.save(video_path)
        
        print("视频已保存，准备调用 startcode函数")

        # 调用startcode，执行后端算法
        data = startcode.startcode(video_path, side, height_real)
        # pr.PoseDetector.close()
        print("完成程序")
        
        # detector = pr.PoseDetector(video_path,height_real,side)
        # # 启动动画
        # detector.start_animation()
        # detector.update_plot(None)
        # detector.main()
        # data = main()
        return jsonify(data)


if __name__ == '__main__':
    host_address = '127.0.0.1'  # 监听本地请求
    # 使用4090端口
    host_port = 5000
    print(f"访问本地服务器地址: http://{host_address}:{host_port}")
    # 运行app应用
    app.run(debug=True, host=host_address, port=host_port)
